import * as mobx from 'mobx';
import { observable, action, toJS } from 'mobx';
import { getSelectNextFlowCondition, getSelectFlowNodeInfo } from '../apis/req';
import { getComsMobx, getLabel } from '../util/convert';
import * as _ from '../util/public/common';

export class SelectNextFlowStore {
    baseParams = {};
    commonParams = {};
    canFlowNextNode = false;// 是否能流到下一节点
    @observable nextNodeIds = '';
    preNextNodeIds = '';
    confirmEvent = null;
    cancelEvent = null;


    @observable condition = [];
    @observable groupList = [];
    @observable form = null;

    @observable nodeInfo = [];
    @observable nodeInfoMap = {};
    @observable nodeScope = '';// 可选择节点的范围
    nodeInfoConfirmEvent = null;
    nodeInfoCancelEvent = null;
    @observable showAllNodeOperators = {};
    @observable operatorChangeDisable = '';

    needDefaultNode = '1';// 是否需默认选中下一节点
    needDefaultoperator = '1';// 是否需要带出默认操作者
    branchNodesMap = {};//流程分支信息
    mustPassNodeIds = [];//分叉起始点指定流转时，必须通过的分支第一个中间点
    @observable nodeAttribute = '0';// 当前节点属性

    @action
    setBaseParams = (params = {}) => {
        this.baseParams = params;
    }

    @action
    setCommonParams = (params = {}) => {
        this.commonParams = params;
    }

    doInit = () => {
        const that = this;

        getSelectNextFlowCondition({ ...this.baseParams, ...this.commonParams }).then((data) => {
            const { conditioninfo } = data;
            this.operatorChangeDisable = data.operatorChangeDisable;
            this.needDefaultNode = data.needDefaultNode;
            this.needDefaultoperator = data.needDefaultoperator;
            this.nodeAttribute = data.nodeattribute;
            this.condition = conditioninfo;

            const { WeaForm } = getComsMobx();
            // this.form = new WeaForm();
            // this.form.initFormFieldObj(conditioninfo);
            this.groupList = [];

            that.getNodeInfo();
        });
    }

    @action('初始化表单相关信息')
    processGroupListInfo = () => {
        const { WeaForm } = getComsMobx();

        this.groupList = [];

        if (this.nodeAttribute != '1') { // 不是分叉起始点
            let conditions = _.cloneDeep(toJS(this.condition));
            let nodeInfo = this.nodeInfoMap[this.nextNodeIds] || {};
            conditions.map((condition) => {
                this.appendHrmSqlWhere(condition, nodeInfo);
                if (condition.domkey != 'nextNode') {
                    condition.domkey = [`${condition.domkey}_${0}`];
                }
            });
            this.groupList[0] = { items: conditions };
        } else { // 分叉起始点
            // 基本信息group
            this.groupList[0] = { title: getLabel(1361, '基本信息'), items: [_.cloneDeep(toJS(this.condition)[0])] };
            // 每个选中节点的group
            this.nextNodeIds && this.nextNodeIds.split(',').map((nodeId, index) => {
                let nodeInfo = this.nodeInfoMap[nodeId] || {};
                let nodeName = nodeInfo.nodeName ? nodeInfo.nodeName : '';
                let conditions = _.cloneDeep(toJS(this.condition));
                // 过滤“下一节点”item
                conditions = conditions.filter(item => item.domkey[0] != 'nextNode');
                conditions.map((condition) => {
                    this.appendHrmSqlWhere(condition, nodeInfo);
                    condition.domkey = [`${condition.domkey}_${index}`];
                });
                this.groupList[index + 1] = { title: `${getLabel(15586, '节点')}：${nodeName}`, items: conditions };
            });
        }
        this.form = new WeaForm();
        this.form.initFormFields(this.groupList);
    }

    appendHrmSqlWhere = (condition, nodeInfo) => {
        //传入对应节点操作者范围
        if(condition.domkey == 'nodeOperator' || condition.domkey == 'ccOperator') {
            if(nodeInfo && nodeInfo.hrmSqlWhere) {
                condition.browserConditionParam.completeParams['sqlwhere'] = nodeInfo.hrmCompleteSqlWhere;
                condition.browserConditionParam.dataParams['sqlwhere'] = nodeInfo.hrmSqlWhere;
            }
        }
    }

    @action
    updateFormByNodeInfo = () => {

        //获取修改下一节点之前，记录的表单值
        let preFormDatas = {};
        let preNextNodeIdArray = this.preNextNodeIds !== '' ? this.preNextNodeIds.split(',') : [];
        if(this.form) {
            preFormDatas = this.form.getFormDatas();
        }

        this.processGroupListInfo();

        this.nextNodeIds.split(',').map((nextNodeId, index) => {
            let operatorValueObj = [];
            let operatorValue = '';
            let operatorValueSpan = '';

            let ccOperatorValueObj = [];
            let ccOperatorValue = '';
            let ccOperatorValueSpan = '';

            let nodeInfo = this.nodeInfoMap[nextNodeId];

            // 默认带出操作者
            if (this.needDefaultoperator == '1') {
                // 操作者
                nodeInfo && nodeInfo.operators && nodeInfo.operators.map((operator) => {
                    operatorValueObj.push({ id: operator.operatorid, name: operator.operatorname });
                    operatorValue += `,${operator.operatorid}`;
                    operatorValueSpan += `,${operator.operatorname}`;
                });
                if (operatorValue.length > 1) {
                    operatorValue = operatorValue.slice(1, operatorValue.length);
                }
                if (operatorValueSpan.length > 1) {
                    operatorValueSpan = operatorValueSpan.slice(1, operatorValueSpan.length);
                }

                // 抄送人
                nodeInfo && nodeInfo.ccOperators && nodeInfo.ccOperators.map((operator) => {
                    ccOperatorValueObj.push({ id: operator.operatorid, name: operator.operatorname });
                    ccOperatorValue += `,${operator.operatorid}`;
                    ccOperatorValueSpan += `,${operator.operatorname}`;
                });
                if (ccOperatorValue.length > 1) {
                    ccOperatorValue = ccOperatorValue.slice(1, ccOperatorValue.length);
                }
                if (ccOperatorValueSpan.length > 1) {
                    ccOperatorValueSpan = ccOperatorValueSpan.slice(1, ccOperatorValueSpan.length);
                }
            }

            let updateParams = {};
            let preIndex = preNextNodeIdArray && preNextNodeIdArray.indexOf(nextNodeId);
            if(preIndex >= 0) {//之前已选择的节点，使用已修改的值
                updateParams[`nodeOperator_${index}`] = preFormDatas[`nodeOperator_${preIndex}`];
                updateParams[`ccOperator_${index}`] = preFormDatas[`ccOperator_${preIndex}`];
                updateParams[`SignType_${index}`] = preFormDatas[`SignType_${preIndex}`];
                updateParams[`canSubmit_${index}`] = preFormDatas[`canSubmit_${preIndex}`];
            } else {
                updateParams[`nodeOperator_${index}`] = {
                    value: operatorValue,
                    valueSpan: operatorValueSpan,
                    valueObj: operatorValueObj,
                };
                updateParams[`ccOperator_${index}`] = {
                    value: ccOperatorValue,
                    valueSpan: ccOperatorValueSpan,
                    valueObj: ccOperatorValueObj,
                };
                updateParams[`SignType_${index}`] = nodeInfo && nodeInfo.signType !== undefined ? nodeInfo.signType : '1';
                updateParams[`canSubmit_${index}`] = nodeInfo && nodeInfo.ccSignType !== undefined ? nodeInfo.ccSignType : '-4';   
            }

            this.form.updateFields(updateParams);
        });
    }

    @action('切换下一节点')
    changeNextNode = (nextNode) => {
        this.setNextNodeIds(nextNode);
        this.updateFormByNodeInfo();
    }

    @action
    getResultParams = () => {
        let result = {};
        let formParams = this.form.getFormParams();
        let formDatas = this.form.getFormDatas();

        result = { ...formParams };
        this.nextNodeIds.split(',').map((key, index) => {
            const nextNodeInfo = this.nodeInfoMap[key];
            result[`selectNodeFlow_nodeId_${index}`] = `${nextNodeInfo.id}_${nextNodeInfo.nodeType}_${nextNodeInfo.nodeAttribute}`;
            result[`selectNodeFlow_operator_${index}`] = formParams[`nodeOperator_${index}`];
        });
        result.selectNodeFlow_canFlowNextNode = this.canFlowNextNode ? '1' : '0';
        result.selectNodeFlow_nodeIds = this.nextNodeIds;

        if(this.operatorChangeDisable == '1') {//不可修改操作者，指定流转为选择节点模式，操作者由后台计算
            result['selectNextFlowMode'] = 2;
        } else {//前台用户指定节点和操作者
            result['selectNextFlowMode'] = 1;
        }
        delete result.nextNode;
        return result;
    }

    @action('获取指定流转的节点信息')
    getNodeInfo = () => {
        getSelectFlowNodeInfo(this.commonParams).then((data) => {
            this.nodeInfo = data.nodeInfo;
            this.branchNodesMap = data.branchNodesMap;
            this.mustPassNodeIds = data.mustPassNodeIds;
            this.nodeScope = data.nodeScope;

            let newNextNodeIds = '';
            let nodeAttributes = [];

            this.nodeInfo.map((node) => {
                this.nodeInfoMap[node.key] = node;
                //需过滤不在可选择范围中的节点
                if(("," + this.nextNodeIds + ",").indexOf(node.id) > -1) {
                    newNextNodeIds += "," + node.id;
                    if(nodeAttributes.indexOf(node.nodeAttribute) == -1) {
                        nodeAttributes.push(node.nodeAttribute)
                    }
                }
            });

            if(newNextNodeIds != '') {
                newNextNodeIds = newNextNodeIds.substring(1);
                //默认下一节点有多个，且节点属性不全为分叉中间点，视为不合法数据，不显示默认节点
                if(nodeAttributes.length > 1 || (newNextNodeIds.split(',').length > 1 && nodeAttributes.length == 1 && nodeAttributes[0] != '2')) {
                    newNextNodeIds = '';
                }

                //非分叉起始点，且下一节点有多个，不显示默认节点
                if(this.nodeAttribute != '1' && newNextNodeIds.split(',').length > 1) {
                    newNextNodeIds = '';
                }
            }

            this.nextNodeIds = newNextNodeIds;

            // 如果未设置自动带出节点，则清空
            if (this.needDefaultNode != '1') {
                this.nextNodeIds = '';
            }
            this.updateFormByNodeInfo();
        });
    }

    setShowAllNodeOperators = (id) => {
        const showAllNodeOperators = { ...this.showAllNodeOperators, [id]: !this.showAllNodeOperators[id] };
        this.showAllNodeOperators = showAllNodeOperators;
    }

    setConfirmEvent = (fun) => {
        this.confirmEvent = fun;
    }

    setCancelEvent = (fun) => {
        this.cancelEvent = fun;
    }

    setNodeInfoConfirmEvent = (fun) => {
        this.nodeInfoConfirmEvent = fun;
    }

    setNodeInfoCancelEvent = (fun) => {
        this.nodeInfoCancelEvent = fun;
    }

    setCanFlowNextNode = (bool) => {
        this.canFlowNextNode = bool;
    }

    setNextNodeIds = (nodeIds) => {
        if (nodeIds.startsWith(',')) {
            nodeIds = nodeIds.substring(1, nodeIds.length);
        }
        if (nodeIds.endsWith(',')) {
            nodeIds = nodeIds.substring(0, nodeIds.length - 1);
        }
        this.preNextNodeIds = this.nextNodeIds;
        this.nextNodeIds = nodeIds;
    }
}
